import 'package:aliplayer_widget/aliplayer_widget_lib.dart';
import 'package:aliplayer_widget/utils/log_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yyshort/common/apis/video_api.dart';
import 'package:yyshort/common/model/video_model.dart';
import 'package:yyshort/pages/ali_player/short_video/short_video/controller.dart';
import 'package:yyshort/pages/foryou/widgets/BottomSheetWidget.dart';
import 'package:yyshort/pages/foryou/widgets/icon_button_widget.dart';
import 'package:yyshort/pages/foryou/widgets/info_card_widget.dart';
import 'package:yyshort/pages/payment/index.dart';

/// 单个播放项组件
class ShortVideoItem extends StatefulWidget {
  /// 视频数据源，支持VideoModel或EpisodeModel
  final dynamic videoInfo;

  final ShortVideoController controller;

  final bool isforyouPage;

  /// 是否自动播放
  final bool autoPlay;

  const ShortVideoItem({
    super.key,
    required this.controller,
    this.autoPlay = true,
    required this.videoInfo,
    required this.isforyouPage,
  }) : assert(
         (isforyouPage && videoInfo is VideoModel) ||
             (!isforyouPage && videoInfo is EpisodeModel),
         "isforyouPage为true时videoInfo必须是VideoModel，为false时必须是EpisodeModel",
       );

  @override
  State<ShortVideoItem> createState() => ShortVideoItemState();
}

class ShortVideoItemState extends State<ShortVideoItem> {
  /// 日志标签
  static const String _tag = "ShortVideoItem";

  /// 播放器组件控制器
  late AliPlayerWidgetController _playerController;

  /// 标记是否已完成初始化
  bool _isInitialized = false;

  /// 根据页面类型获取对应的VideoModel
  VideoModel get videoModel {
    assert(widget.isforyouPage, "只有在isforyouPage为true时才能访问videoModel");
    return widget.videoInfo as VideoModel;
  }

  /// 根据页面类型获取对应的EpisodeModel
  EpisodeModel get episodeModel {
    assert(!widget.isforyouPage, "只有在isforyouPage为false时才能访问episodeModel");
    return widget.videoInfo as EpisodeModel;
  }

  /// 获取视频ID（根据不同模型类型）
  String get _videoId {
    return widget.isforyouPage
        ? videoModel.id.toString()
        : episodeModel.id.toString();
  }

  /// 获取视频播放地址（根据不同模型类型）
  String get _videoUrl {
    if (widget.isforyouPage) {
      return videoModel.url ?? "";
    } else {
      return episodeModel.url ?? "";
    }
  }

  /// 获取视频封面地址（根据不同模型类型）
  String get _coverUrl {
    if (widget.isforyouPage) {
      return videoModel.imgUrl ?? "";
    } else {
      return episodeModel.imgUrl ?? "";
    }
  }

  @override
  void initState() {
    super.initState();
    debugPrint("[$_tag][lifecycle][initState]: $_videoId");
    logi(55555.toString());

    // 初始化播放器组件控制器
    _playerController = AliPlayerWidgetController(context);
    debugPrint("这是一条调试日志");

    // 可以添加标签区分不同类型的日志
    debugPrint("[API] 正在请求数据...");
    debugPrint("[UI] 页面构建完成");

    // 先执行必要的请求，完成后再初始化播放器
    _performInitialRequest().then((_) {
      if (mounted) {
        _initializePlayer();
      }
    });
  }

  /// 执行初始化前的请求
  Future<void> _performInitialRequest() async {
    debugPrint("[$_tag][_performInitialRequest]: 开始执行初始化请求 for $_videoId");

    // 只有非推荐页(剧集页)才需要执行此请求
    if (!widget.isforyouPage) {
      try {
        // 使用episodeModel获取ID
        int tempVideoID = episodeModel.videoId!;
        int tempEpisode_id = episodeModel.id!;

        // 获取视频详情
        EpisodeModel model = await VideoAPI.video_episode_content(
          tempVideoID,
          tempEpisode_id,
        );

        // 更新视频信息
        episodeModel.url = model.url;
        episodeModel.imgUrl = model.imgUrl;

        debugPrint("[$_tag][_performInitialRequest]: 请求完成 for $_videoId");
      } catch (e) {
        debugPrint("[$_tag][_performInitialRequest]: 请求出错: $e");
      }
    }
  }

  /// 初始化播放器
  void _initializePlayer() {
    debugPrint("[$_tag][_initializePlayer]: 开始初始化播放器 for $_videoId");

    // 设置播放器视频源
    final videoSource = VideoSourceFactory.createUrlSource(_videoUrl);

    // 设置播放器组件数据
    final data = AliPlayerWidgetData(
      sceneType: SceneType.listPlayer,
      videoSource: videoSource,
      // coverUrl: _coverUrl,
      autoPlay: widget.autoPlay,
    );
    _playerController.configure(data);

    setState(() {
      _isInitialized = true;
    });

    print("[$_tag][_initializePlayer]: 播放器初始化完成 for $_videoId");
  }

  @override
  void dispose() {
    debugPrint("[$_tag][lifecycle][dispose]: $_videoId");

    // 销毁播放控制器
    _playerController.destroy();

    super.dispose();
  }

  /// 暂停播放
  void pause() {
    debugPrint("[$_tag][paused]: $_videoId");
    _playerController.pause();
  }

  /// 恢复播放
  void resume() {
    debugPrint("[$_tag][resumed]: $_videoId");
    _playerController.play();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.black,
      alignment: Alignment.center,
      child: _buildPlayWidget(),
    );
  }

  /// 构建播放器组件
  Widget _buildPlayWidget() {
    // 在初始化完成前显示加载状态
    if (!_isInitialized) {
      return Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
        ),
      );
    }

    return AliPlayerWidget(
      _playerController,
      overlays: [
        // 信息卡片 - 只在推荐页显示
        if (widget.isforyouPage)
          Positioned(
            left: 0,
            bottom: 15.h,
            width: ScreenUtil().screenWidth / 4 * 3,
            child: InfoCardWidget(
              title: videoModel.name!,
              detail: videoModel.description!,
            ),
          ),

        // 右侧图标按钮 - 贴靠右侧中心偏下
        Align(
          alignment: Alignment.centerRight,
          child: Padding(
            padding: EdgeInsets.only(right: 15),
            child: IconButtonWidget(
              width: 30.w,

              //收藏
              onStarTap: () {},

              //喜欢
              onHeartTap: () {},

              //选集
              onTvTap: () {
                // showModalBottomSheet(
                //   context: context,
                //   builder: (context) => BottomSheetWidget(
                //     height: ScreenUtil().screenHeight / 4 * 3,
                //     secondPartText:
                //         'All ${widget.controller.state.videoInfoList.length} Episode',
                //     isSecondPartHidden: false,
                //     firstPartTextAlign: TextAlign.left,
                //     customChild: ScrollableListWidget(
                //       items: List.generate(
                //         widget.controller.state.videoInfoList.length,
                //         (index) => "Episode$index",
                //       ),
                //     ),
                //   ),
                // );
              },

              //分享
              onArrowTap: () {
                if (!Get.isRegistered<PaymentController>()) {
                  Get.put(PaymentController());
                }
              },
            ),
          ),
        ),
      ],
    );
  }
}
